<template>
  <div class="dialog_box">
    <el-dialog v-model="appDialog.visible" width="1000px" title="选择客户" @closed="onClose" destroy-on-close>
      <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
      <ZwTable
        ref="tableRef"
        tabH="400px"
        class="table-box"
        :multiple="appDialog.multiple"
        :selectedIds="props.selectedIds"
        :option="tableOption"
        :rowKey="getRowKey"
        :fetch-params="state.searchParams"
        :fetch-api="fetchApi()"
        @selection-change="handleSelectionChange"
        @radioChange="radioChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="appDialog.visible = false">取消</el-button>
          <el-button @click="onSubmit" type="primary">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx">
  import { getCustomerOpenseaSelect } from '@/api/customer/manage/list'
  import { stageList, sourceList } from '@/view/customer/manage/configure/api'
  import { getSetionId } from '@/utils/utils'
  import { getCenterCustomerListPost, getCenterCustomerList } from '@/api/customerCenter'
  import { Picture as IconPicture } from '@element-plus/icons-vue'
  import { nextTick, ref, watch, reactive, computed } from 'vue'
  import { isTemplateElement } from '@babel/types'
  import { deepCopy } from '@/utils/helper'
  import ZwSearchForm from '@/components/zw/search-form/SearchForm'
  import ZwTable from '@/components/zw/table/Table'

  const emit = defineEmits(['submit'])
  const props = defineProps(['sync_type', 'selectedIds'])
  const appDialog = reactive<any>({
    visible: false,
    multiple: false, // 是否多选
    row: { id: '' }
  })
  const tableData = ref([])
  const tableRef = ref<any>(null)
  const DepartRef = ref<any>(null)
  const PaginationRef = ref<any>()
  const employeeList = ref<any>([]) // 创建人options
  const formData = reactive<any>({
    mobile_or_name: '', // 名称
    seas_id: '', // 公海
    created_time: [],
    is_wx_work: -1,
    work_user_ids: [],
    stage: 0,
    cust_status: -1,
    touch_mode: -1,
    type:props.sync_type || '',
    page: 1,
    page_size: 15
  })

  const searchOption = computed(() => {
    return [
      {
        label: '客户姓名',
        name: 'mobile_or_name',
        value: '',
        type: 'input',
        width: '280px',
        placeholder: '请输入客户名称|手机号搜索'
      },
      {
        label: '客户类型',
        name: 'is_wx_work',
        value: '',
        type: 'select',
        placeholder: '请选择客户类型',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve([
              { name: '全部', id: '-1' },
              { name: '企微客户', id: '1' },
              { name: '非企微客户', id: '0' }
            ])
          })
        },
        formatOption: (v: { name: any; id: any }) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '归属员工',
        name: 'work_user_ids',
        value: [],
        type: 'select',
        placeholder: '请选择归属员工',
        multiple: true,
        popperClass: 'zw-hide_select_option',
        isUserSelect: true,
        formatOption: (v) => ({
          label: v.name,
          value: v.id
        })
      },
      {
        label: '客户公海',
        name: 'seas_id',
        value: '',
        type: 'select',
        placeholder: '请选择客户公海',
        multiple: true,
        collapseTags: true,
        filterable: true,
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve(selectData.value)
          })
        }
      },
      {
        label: '客户阶段',
        name: 'stage',
        value: [],
        type: 'select',
        placeholder: '请选择客户阶段',
        fetchOptionApi: () => {
          return new Promise((resolve) => {
            resolve(stageListOptList.value)
          })
        }
      },

      {
        label: '创建时间',
        name: 'created_time',
        value: [],
        type: 'datePicker',
        datePickerType: 'daterange',
        datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
      }
    ]
  })
  const tableOption = computed(() => {
    const arr = [
      {
        type: 'selection',
        width: 55,
        fixed: 'left',
        reserveSelection: true
      },
      {
        width: 55,
        fixed: 'left',
        isRadio: true
      },
      {
        prop: 'date',
        label: '客户姓名',
        render({ row }) {
          return (
            <>
              <div vShow={row.type == 1} class="cust_info">
                <img class="left" src={row.cust_baseinfo?.avatar} alt="" />
                <div> {row.cust_baseinfo?.name || '--'}</div>
              </div>
              <div vShow={row.type != 1} class="cust_info">
                <img class="left" src={row?.avatar} alt="" />
                <div> {row.crop_name || '--'}</div>
              </div>
            </>
          )
        }
      },
      {
        prop: 'assign_employees',
        label: '归属员工',
        width: 100,
        render({ row }) {
          return <span>{row.assign_employees || '--'}</span>
        }
      },
      {
        prop: 'current_stage_name',
        label: '客户阶段',
        width: 200,
        render({ row }) {
          return <span>{row.current_stage_name || '--'}</span>
        }
      },
      {
        prop: 'created_at',
        label: '创建时间',
        width: 170,
        render({ row }) {
          return <span>{row.created_at || '--'}</span>
        }
      }
    ]
    if (!appDialog.multiple) {
      arr.splice(0, 1)
    } else {
      arr.splice(1, 1)
    }
    return arr
  })
  const getRowKey = (row: any) => {
    return row.id
  }

  const defaultParams = reactive({
    mobile_or_name: '', // 名称
    is_wx_work: -1,
    work_user_ids: [],
    seas_id: '', // 公海
    stage: 0,
    created_time: [],
    cust_status: -1,
    touch_mode: -1,
    type: props.sync_type || '',
  })
  const state = reactive({
    searchParams: deepCopy(defaultParams)
  })
  const search = (data: any) => {
    tableRef.value.getTable().clearSelection()
    const res = { ...defaultParams, ...data }
    state.searchParams = { ...deepCopy(res) }
  }
  const reset = (v?: any) => {
    tableRef.value.getTable().clearSelection()
    state.searchParams = deepCopy(defaultParams)
  }
  const fetchApi = () => {
    // 获取文件列表
    getTableH()
    return getCenterCustomerListPost
  }
  const getTableH = () => {
    nextTick(() => {
      tableRef.value.getTableH()
    })
  }
  const radioChange = (v: any) => {
    if (v) {
      appDialog.row = v
    }
  }

  const stageListOptList = ref<any>([]) //客户阶段字典

  // 获取客户阶段字典
  const stageListFun = () => {
    stageList({ page: 1, page_size: 99999 }).then((r: any) => {
      stageListOptList.value = r || []
    })
  }
  stageListFun()
  const checkList = ref([])
  const handleSelectionChange = (v: any) => {
    checkList.value = v
  }

  const onReset = () => {
    formData.mobile_or_name = ''
    formData.seas_id = ''
    formData.created_time = []
    formData.is_wx_work = -1
    formData.work_user_ids = []
    formData.stage = 0
    formData.touch_mode = -1
    formData.page = 1
    formData.page_size = 15
  }
  const onSubmit = () => {
    if (checkList.value.length || appDialog.row.id) {
      emit('submit', appDialog.multiple ?  checkList.value : appDialog.row  )
      appDialog.visible = false
    }
  }
  watch(
    () => appDialog.visible,
    (v) => {
      if (v) {
        onReset()
      }
    }
  )
  const onClose = () => {
    formData.mobile_or_name = ''
    formData.is_wx_work = -1
    formData.work_user_ids = []
    formData.stage = 0
    formData.touch_mode = -1
    formData.page = 1
    formData.page_size = 15
    appDialog.row.id = ''
  }
  const selectData = ref<any>([])
  const onGetSelectData = () => {
    getCustomerOpenseaSelect({ type: 2 }).then((res: any) => {
      selectData.value = res
    })
  }
  onGetSelectData()
  defineExpose({
    appDialog
  })
</script>

<style scoped lang="scss">
  .dialog_box {
    :deep(.el-dialog) {
      // height: 600px;
      .el-dialog__header {
        border-bottom: 1px solid #eaeaea;
      }
      .el-dialog__body {
        padding: 15px;
        border-bottom: 1px solid #eaeaea;
      }
    }

    .container {
      padding: 20px;
      background-color: #f9f9f9;
      .item_box {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
        grid-gap: 20px;
        .el-form-item {
          :deep(.el-input__inner) {
            width: 100%;
          }
          margin: 0;
          .el-select {
            width: 100%;
          }
          .amount {
            display: grid;
            grid-template-columns: 15px 1fr 15px 1fr;
            grid-gap: 10px;
            .el-input-number {
              width: auto;
            }
          }
          :deep(.el-date-editor--datetime) {
            width: 100%;
          }
          .btn_box {
            text-align: right;
          }
        }
      }
    }
  }
  .btn_box {
    margin-top: 20px;
    text-align: right;
  }
  .table_box {
    margin-top: 16px;


  }
  :deep(.cust_info) {
      display: grid;
      grid-template-columns: 48px 1fr;
      align-items: center;
      grid-gap: 7px;
      .left {
        width: 48px;
        height: 48px;
        object-fit: cover;
        font-size: 48px;
        border-radius: 4px;
        display: grid;
        place-content: center;
      }
      .right {
        // padding: 5px 0;
        .right_t {
          font-size: 14px;
        }
        .right_b {
          margin-top: 10px;
          font-size: 12px;
          color: #969696;
        }
      }
    }
  :deep(.el-table) {
    --el-table-current-row-bg-color: #fffaf9
    --el-table-row-hover-bg-color: #fffaf9;
  }
  .date-picker-box {
    :deep(.el-form-item__content){
      display: flex;
    }
  }
  // .el-table--enable-row-hover .el-table__body tr:hover > td {
  //   background-color: #212e3e !important;
  // }
</style>
